<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';

const props = defineProps({
  index: {
    type: Number,
    required: true
  }
});

// 响应式数据
const clientId = ref(generateRandomId());
const socket = ref(null);
const status = ref('idle'); // idle, waiting, active, selecting
const message = ref('点击开始排队');
const isConnected = ref(false);

// 计算属性
const statusText = computed(() => {
  switch (status.value) {
    case 'idle': return '空闲';
    case 'waiting': return '排队中';
    case 'active': return '可选号';
    case 'selecting': return '选号中';
    default: return '未知';
  }
});

const componentClass = computed(() => {
  return {
    'queue-component': true,
    'waiting': status.value === 'waiting',
    'active': status.value === 'active',
    'selecting': status.value === 'selecting'
  };
});

const showStartButton = computed(() => status.value === 'idle');
const showSelectButton = computed(() => status.value === 'active');
const showEndButton = computed(() => status.value === 'selecting');

const displayClientId = computed(() => {
  return `组件 ${props.index} (ID: ${clientId.value.substr(-8)})`;
});

// 方法
function generateRandomId() {
  return 'client_' + Math.random().toString(36).substr(2, 9) + '_' + Date.now();
}

function connectWebSocket() {
  if (socket.value && socket.value.readyState === WebSocket.OPEN) {
    return;
  }
  
  socket.value = new WebSocket('ws://localhost:8080/queue');
  
  socket.value.onopen = () => {
    isConnected.value = true;
    console.log(`组件 ${props.index} WebSocket连接已建立`);
  };
  
  socket.value.onmessage = (event) => {
    const data = JSON.parse(event.data);
    handleMessage(data);
  };
  
  socket.value.onclose = () => {
    isConnected.value = false;
    console.log(`组件 ${props.index} WebSocket连接已关闭`);
  };
  
  socket.value.onerror = (error) => {
    console.error(`组件 ${props.index} WebSocket错误:`, error);
    message.value = '连接错误，请重试';
  };
}

function sendMessage(type) {
  if (socket.value && socket.value.readyState === WebSocket.OPEN) {
    const msg = {
      type: type,
      clientId: clientId.value
    };
    socket.value.send(JSON.stringify(msg));
  }
}

function handleMessage(data) {
  switch (data.type) {
    case 'CAN_START':
      status.value = 'active';
      message.value = data.message;
      break;
    case 'WAITING':
      status.value = 'waiting';
      message.value = data.message;
      break;
    case 'LEFT_QUEUE':
      status.value = 'idle';
      message.value = '已离开队列，点击开始排队';
      break;
    case 'NOT_IN_QUEUE':
      status.value = 'idle';
      message.value = '点击开始排队';
      break;
  }
}

function startQueue() {
  connectWebSocket();
  
  // 等待连接建立后发送消息
  const checkConnection = () => {
    if (socket.value && socket.value.readyState === WebSocket.OPEN) {
      sendMessage('JOIN_QUEUE');
    } else {
      setTimeout(checkConnection, 100);
    }
  };
  
  checkConnection();
}

function startSelecting() {
  status.value = 'selecting';
  message.value = '正在选号中...';
}

function endSelecting() {
  sendMessage('LEAVE_QUEUE');
  status.value = 'idle';
  message.value = '选号完成，点击开始排队';
  
  if (socket.value) {
    socket.value.close();
  }
}

// 生命周期
onUnmounted(() => {
  if (socket.value) {
    socket.value.close();
  }
});
</script>

<template>
  <div :class="componentClass">
    <div class="component-header">
      <span class="component-id">{{ displayClientId }}</span>
      <span :class="'status ' + status">{{ statusText }}</span>
    </div>
    <div class="message">{{ message }}</div>
    <div class="buttons">
      <button 
        v-if="showStartButton"
        class="btn-start" 
        @click="startQueue"
        :disabled="status !== 'idle'">
        开始排队
      </button>
      <button 
        v-if="showSelectButton"
        class="btn-select" 
        @click="startSelecting">
        开始选号
      </button>
      <button 
        v-if="showEndButton"
        class="btn-end" 
        @click="endSelecting">
        结束选号
      </button>
    </div>
    <div :class="'connection-status ' + (isConnected ? 'connected' : 'disconnected')">
      {{ isConnected ? '已连接' : '未连接' }}
    </div>
  </div>
</template>

<style scoped>
.queue-component {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  border: 2px solid #e0e0e0;
  transition: all 0.3s ease;
}

.queue-component.active {
  border-color: #4CAF50;
  background-color: #f8fff8;
}

.queue-component.waiting {
  border-color: #ff9800;
  background-color: #fff8f0;
}

.queue-component.selecting {
  border-color: #2196F3;
  background-color: #f0f8ff;
}

.component-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.component-id {
  font-weight: bold;
  color: #333;
}

.status {
  padding: 5px 10px;
  border-radius: 15px;
  font-size: 12px;
  font-weight: bold;
}

.status.idle {
  background-color: #e0e0e0;
  color: #666;
}

.status.waiting {
  background-color: #ff9800;
  color: white;
}

.status.active {
  background-color: #4CAF50;
  color: white;
}

.status.selecting {
  background-color: #2196F3;
  color: white;
}

.message {
  margin: 10px 0;
  padding: 10px;
  border-radius: 5px;
  background-color: #f0f0f0;
  min-height: 20px;
}

.buttons {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}

button {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-weight: bold;
  transition: background-color 0.3s;
}

.btn-start {
  background-color: #4CAF50;
  color: white;
}

.btn-start:hover:not(:disabled) {
  background-color: #45a049;
}

.btn-start:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.btn-select {
  background-color: #2196F3;
  color: white;
}

.btn-select:hover {
  background-color: #1976D2;
}

.btn-end {
  background-color: #f44336;
  color: white;
}

.btn-end:hover {
  background-color: #d32f2f;
}

.connection-status {
  font-size: 12px;
  margin-top: 10px;
}

.connected {
  color: #4CAF50;
}

.disconnected {
  color: #f44336;
}
</style>